<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>sleep的实现方法</title>
  <!-- https://www.jb51.net/article/185441.htm -->
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      min-height: inherit;
    }
  </style>
</head>

<body>
  <div></div>
</body>
<script>
  "use strict"; {
    {
      // sleep函数: 使程序暂停指定的时间，起到延时的效果

      // 通过死循环来阻止代码执行，同时不停比对是否超时。
      // 缺点: 以上的代码不会让线程休眠，而是通过高负荷计算使cpu无暇处理其他任务。这样做的缺点是在sleep的过程中其他所有的任务都会被暂停，包括dom的渲染。所以sleep的过程中程序会处于假死状态，并不会去执行其他任务
      let sleep1 = time => {
        let startTime = +new Date()
        let endTime = startTime
        do {
          endTime = +new Date()
        } while ((endTime - startTime) < time)
      }
      console.log("1")
      // sleep1(1 * 1000)
      console.log("2")
    }; {
      // 2.基于Promise的sleep
      let sleep2 = time => {
        return new Promise(resolve => setTimeout(resolve, time))
      }

      console.log("1")
      console.time("time")
      sleep2(1 * 1000).then(() => {
        console.log("2")
        console.timeEnd("time")
      })
    }; {
      // 3.基于async函数的sleep
      let sleep3 = time => {
        return new Promise(resolve => setTimeout(resolve, time))
      }
      (async () => {
        // console.log("sleep3")
        console.log("1", "sleep3")
        console.time("sleep3")
        await sleep3(1 * 1000)
        console.log("2")
        console.timeEnd("sleep3")
      })()
    };
  }
</script>

</html>